/*
* 表单验证处理
* 支持类型[dataType]: Email,Phone,Mobile,Url,IdCard,Number,Zip,QQ,Integer,Double,English,Chinese,DateTime
*                    Date,Repeat,Range,Compare,Custom,Group,Limit,LimitB,SafeString,CompareTime
* require:是否必填 
* label :提示信息的主题
* min:最小值
* max:最大值
* operator:操作符NotEqual:!=,GreaterThan:>,GreaterThanEqual:>=,LessThan:<,LessThanEqual:<=
* to:比较的值或输入框对象
* 使用方法 Validator.Validate(form对象,1)
* <body onload="documentOnload()">
* 添加了自定义类型
* 自定义类型以UF_开头
* 应该添加相应的处理函数如
	function UF_MaterialId_Validate(msgs,obj){
		if (obj.value.length>5){
		   msgs[0]=obj.label+'长度不能大于【5】';
		   return false;
		}
	  return true;
	}
  其中参数msgs是一个数组,第一个值对应的是返回的异常信息
  其中参数obj是对应的对象
* 2009-3-17 13:35

*/
 var error_not_empty="的值不能为空";
 var error_not_phone="的值不是合法的电话号码的格式";
 var error_not_email="的值不是合法的Email格式";
 var error_not_integer="的值不是整数";
 var error_not_double="的值不是数值"
 var error_errormessage="以下原因导致操作失败";
 var error_not_long="字数过长";
try{
	 if(Global){
		 if (Global.error_not_empty!=null){
			 error_not_empty=Global.error_not_empty;
		 }
		 if (Global.error_not_phone!=null){
			 error_not_phone=Global.error_not_phone;
		 }
		 if (Global.error_not_email!=null){
			 error_not_email=Global.error_not_email;
		 }
		 if (Global.error_not_integer!=null){
			 error_not_integer=Global.error_not_integer;
		 }
		 if (Global.error_not_double!=null){
			 error_not_double=Global.error_not_double;
		 }
		 if (Global.error_errormessage!=null){
			 error_errormessage=Global.error_errormessage;
		 }
		 if (Global.error_not_long!=null){
			 error_not_long=Global.error_not_long;
		 }
	 }
 }catch(e){}
Validator = {
	Require:/.+/,
    Email:/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/,
    Phone:/^((\(\d{3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}$/,
    Mobile:/^((\(\d{3}\))|(\d{3}\-))?(13|15|013|015)\d{9}$/,
    Url:/^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/,
    IdCard:/^\d{15}(\d{2}[A-Za-z0-9])?$/,Currency:/^\d+(\.\d+)?$/,
    Number:/^\d+$/,
    Zip:/^[1-9]\d{6}$/,
    QQ:/^[1-9]\d{4,10}$/,
    Integer:/^[-\+]?\d+$/,
    Double:/^[-\+]?\d+(\.\d+)?$/,
    English:/^[A-Za-z]+$/,
    Chinese:/^[\u0391-\uFFE5]+$/,
    Safe:/^(?:\w*\s*)+$/,///^(([A-Z]*|[a-z]*|\d*|[-_\~!@#\$%\^&\*\.\(\)\[\]\{\}<>\?\\\/\'\"]*)|.{0,5})$|\s/,
    DateTime:/^((\d{4}-(((0[13578]|1[02])-(0[1-9]|1[0-9]|2[0-9]|3[01]))|((0[469]|11)-(0[1-9]|1[0-9]|2[0-9]|30))|((02)-(0[1-9]|1[0-9]|2[0-8]))))|(((([0-9]{2})(0[48]|[2468][048]|[13579][26]))|((0[48]|[2468][048]|[13579][26])00))-02-29))$/,
    IsSafe:function(str) {
        return this.Safe.test(str);
    },
    SafeString:"(function(validator){with(validator){TempMsg[0]='的值不能包含非法字符';return IsSafe(value);}})(this)",
    Limit:"(function(validator){with(validator){TempMsg[0]='的字符数不能小于['+(getAttribute('min')?getAttribute('min'):'0')+']也不能大于['+getAttribute('max')+']';return limit(value.length,getAttribute('min'), getAttribute('max'));}})(this)",
    LimitB:"(function(validator){with(validator){TempMsg[0]='的字节数不能小于['+(getAttribute('min')?getAttribute('min'):'0')+']也不能大于['+getAttribute('max')+']';return limit(LenB(value), getAttribute('min'), getAttribute('max'));}})(this)",
    Date:"(function(validator){with(validator){TempMsg[0]='的值不是合法的日期格式';return IsDate(value,getAttribute('format'));}})(this)",
    Repeat:"(function(validator){with(validator){TempMsg[0]='与'+document.getElementsByName(getAttribute('to'))[0].label+'的值不相等';return value == document.getElementsByName(getAttribute('to'))[0].value;}})(this)",
    Range:"(function(validator){with(validator){TempMsg[0]='的值不能小于['+(getAttribute('min')?getAttribute('min'):'0')+']也不能大于['+getAttribute('max')+']';return parseFloat(getAttribute('min')) <= parseFloat(value) && parseFloat(value) <= parseFloat(getAttribute('max'));}})(this)",
    Compare:"(function(validator){with(validator){return compare(value,getAttribute('operator'),getAttribute('to'));}})(this)",
    CompareTime:"(function(validator){with(validator){return compareTime(getAttribute('to'),value,getAttribute('tip'));}})(this)",
    Custom:"(function(validator){with(validator){TempMsg[0]='';return Exec(value, getAttribute('regexp'));}})(this)",
    Group:"(function(validator){with(validator){TempMsg[0]='选中的数量不能小于['+(getAttribute('min')?getAttribute('min'):'0')+']也不能大于['+getAttribute('max')+']';return MustChecked(getAttribute('name'), getAttribute('min'), getAttribute('max'));}})(this)",
    ErrorItem:[document.forms[0]],
    ErrorMessage:[error_errormessage+"：\t\t\t\t"],
	RegularMsg:{Require:error_not_empty,
				Email:error_not_email,
				Phone:error_not_phone,
				Mobile:"的值不是合法的手机号码格式",
				Url:"的值不是合法的Url格式",
				IdCard:"的值不是合法的身份证格式",
				Number:"的值不是有效数字",
				Zip:"的值不是合法的邮编格式",
				QQ:"的值不是合法的QQ号码格式",
				Integer:error_not_integer,
				Double:error_not_double,
				English:"的值不全为字母",
				Chinese:"的值不全为汉字",
				UnSafe:"的值不是合法的格式",
				DateTime:"的值不是合法的日期格式"},
	TempMsg:[""],
    Validate:function(theForm, mode) {
        var obj = theForm || event.srcElement;
		if (obj!=null){
             if (obj.tagName.toUpperCase()!="FORM"){
				 obj=obj.form;
             }
		}
		if (obj==null || obj.tagName.toUpperCase()!="FORM"){
            alert("没有定义form对象");
			return false;
		}

		var count = obj.elements.length;
        this.ErrorMessage.length = 1;
        this.ErrorItem.length = 1;
        this.ErrorItem[0] = obj;
        for (var i = 0; i < count; i++) {
			this.TempMsg[0]='';
            with (obj.elements[i]) {
            	if(obj.elements[i].type == undefined)continue;
				this.ClearState(obj.elements[i]);
				if (value == ""){
					if (getAttribute("require")=="true"){
                    	this.AddError(i, getAttribute("label")+error_not_empty);
					}
                    continue;
				}
				
                var _dataTypes = getAttribute("dataType");
				if (_dataTypes==null || _dataTypes=="") continue;
				var dataTypeArr=_dataTypes.split(";");
				for (var t=0;t<dataTypeArr.length;t++){
					var _dataType=dataTypeArr[t];
					if (_dataTypes=="") continue;
					if (typeof(_dataType) == "object" || typeof(this[_dataType]) == "undefined") continue;
					if (_dataType.indexOf("UF_")!=-1){
						try{
						   if (!this[_dataType](this.TempMsg,obj.elements[i])){
							   this.AddError(i,this.TempMsg[0]);
						   }
						}catch(e){
							//this.AddError(i, getAttribute("label")+this.TempMsg[0]);
						}
						continue;
					}
					switch (_dataType) {
						case"Date":
						case"Repeat":
						case"Range":
						case"Compare":
						case"Custom":
						case"Group":
						case"Limit":
						case"LimitB":
						case"SafeString":
							if (!eval(this[_dataType])){
								this.AddError(i, (getAttribute("label")?getAttribute("label"):getAttribute("name"))+this.TempMsg[0]);
							}
							break;
						case"CompareTime":{
							var errorstr = eval(this[_dataType]);
							if (errorstr != "") {
								this.AddError(i, errorstr);
							}
							break;
						}
						default:
							if (!this[_dataType].test(value)) {
							   if (typeof(this.RegularMsg[_dataType]) != "undefined"){
								   this.AddError(i, (getAttribute("label")?getAttribute("label"):getAttribute("name"))+""+this.RegularMsg[_dataType]);
							   }else{  
								   this.AddError(i, getAttribute("label"));
							   }
							}
							break;
					}
				}
				/*
                if (typeof(_dataType) == "object" || typeof(this[_dataType]) == "undefined") continue;
				if (_dataType.indexOf("UF_")!=-1){
					try{
					   if (!this[_dataType](this.TempMsg,obj.elements[i])){
						   this.AddError(i,this.TempMsg[0]);
					   }
					}catch(e){
						//this.AddError(i, getAttribute("label")+this.TempMsg[0]);
					}
					continue;
				}
				
                switch (_dataType) {
                    case"Date":
                    case"Repeat":
                    case"Range":
                    case"Compare":
                    case"Custom":
                    case"Group":
                    case"Limit":
                    case"LimitB":
                    case"SafeString":
                        if (!eval(this[_dataType])){
                            this.AddError(i, (getAttribute("label")?getAttribute("label"):getAttribute("name"))+this.TempMsg[0]);
                        }
                        break;
                    case"CompareTime":{
                        var errorstr = eval(this[_dataType]);
                        if (errorstr != "") {
                            this.AddError(i, errorstr);
                        }
                        break;
                    }
                    default:
                        if (!this[_dataType].test(value)) {
						   if (typeof(this.RegularMsg[_dataType]) != "undefined"){
							   this.AddError(i, (getAttribute("label")?getAttribute("label"):getAttribute("name"))+""+this.RegularMsg[_dataType]);
						   }else{  
                               this.AddError(i, getAttribute("label"));
						   }
                        }
                        break;
                }
				*/
            }
        }
        
        if (this.ErrorMessage.length > 1) {
            mode = mode || 1;
            var errCount = this.ErrorItem.length;
            switch (mode) {
                case 2:
                    for (var i = 1; i < errCount; i++)
                        this.ErrorItem[i].style.color = "red";
                case 1:
                    alert(this.ErrorMessage.join("\n"));
                    try{
                    	this.ErrorItem[1].focus();
                    }catch(e){
							//this.AddError(i, getAttribute("label")+this.TempMsg[0]);
					} 
                    break;
                case 3:
                    for (var i = 1; i < errCount; i++) {
                        try {
                            var span = document.createElement("SPAN");
                            span.id = "__ErrorMessagePanel";
                            span.style.color = "red";
                            this.ErrorItem[i].parentNode.appendChild(span);
                            span.innerHTML = this.ErrorMessage[i].replace(/\d+:/, "*");
                        } catch(e) {
                            alert(e.description);
                        }
                    }
                    this.ErrorItem[1].focus();
                    break;
                default:
                    alert(this.ErrorMessage.join("\n"));
                    break;
            }
            return false;
        }
        return true;
    },
    limit:function(len, min, max) {
        min = min || 0;
        max = max || Number.MAX_VALUE;
        return min <= len && len <= max;
    },
    LenB:function(str) {
        return str.replace(/[^\x00-\xff]/g, "**").length;
    },
    ClearState:function(elem) {
        with (elem) {
            if (style.color == "red") style.color = "";
            var lastNode = parentNode.childNodes[parentNode.childNodes.length - 1];
            if (lastNode.id == "__ErrorMessagePanel") parentNode.removeChild(lastNode);
        }
    },
    AddError:function(index, str) {
        this.ErrorItem[this.ErrorItem.length] = this.ErrorItem[0].elements[index];
        this.ErrorMessage[this.ErrorMessage.length] = this.ErrorMessage.length + ":" + str;
    },
    Exec:function(op, reg) {
        return new RegExp(reg, "g").test(op);
    },
    compare:function(op1, operator, sop2) {
        var op2;
        if (isNaN(sop2))
            op2 = document.getElementById(sop2).value;
        else
            op2 = sop2;
        if (isNaN(op1) || isNaN(op2)) {
            return false;
        } else {
            op1 = Number(op1);
            op2 = Number(op2);
            switch (operator) {
                case"NotEqual":
					this.TempMsg[0]='的值不等于['+op2+']!';
                    return(op1 != op2);
                case"GreaterThan":
					this.TempMsg[0]='的值不大于['+op2+']!';
                    return(op1 > op2);
                case"GreaterThanEqual":
					this.TempMsg[0]='的值不大于等于['+op2+']!';
                    return(op1 >= op2);
                case"LessThan":
					this.TempMsg[0]='的值不小于['+op2+']!';
                    return(op1 < op2);
                case"LessThanEqual":
					this.TempMsg[0]='的值不小于等于['+op2+']!';
                    return(op1 <= op2);
                default:
					this.TempMsg[0]='的值不等于['+op2+']!';
                    return(op1 == op2);
            }
        }
    },
    compareTime:function(date1, dtvalue2, tipmes) {
        var strtip = new Array();
        strtip[0] = "开始时间";
        strtip[1] = "结束时间";
        if (tipmes != "" || tyepof(tipmes) != "undefined"){
            strtip = tipmes.split(",");
        }
        var errormsg = "";
        var dateformat = /^\d{4}(?:-\d{1,2}){2}$/;
        var dtvalue1 = document.getElementById(date1).value;
        if (dtvalue1 != "" && !this["DateTime"].test(dtvalue1)){
            errormsg = strtip[0] + "不是合法的日期格式";
            return errormsg;
        }
        if (dtvalue2 != "" && !this["DateTime"].test(dtvalue2)){
            errormsg = strtip[1] + "不是合法的日期格式";
            return errormsg;
        }
        if (dtvalue2 != "" && dtvalue1 == ""){
            errormsg = "缺少" + strtip[0];
            return errormsg;
        }
        if (dtvalue2 == "" && dtvalue1 != ""){
            errormsg = "缺少" + strtip[1];
            return errormsg;
        }
        var strdt1 = (dtvalue1).replace(/-/g, "/");
        var strdt2 = (dtvalue2).replace(/-/g, "/");
        var time1 = new Date(strdt1);
        var time2 = new Date(strdt2);
        var datediff = time2 - time1;
        if (datediff < 0)
        {
            errormsg = strtip[1] + "不能早于" + strtip[0];
            return errormsg;
        }
        return errormsg;
    },
    MustChecked:function(name, min, max) {
        var groups = document.getElementsByName(name);
        var hasChecked = 0;
        min = min || 1;
        max = max || groups.length;
        for (var i = groups.length - 1; i >= 0; i--)
            if (groups[i].checked)hasChecked++;
        return min <= hasChecked && hasChecked <= max;
    },
    IsDate:function(op, formatString) {
        formatString = formatString || "ymd";
        var m,year,month,day;
        switch (formatString) {
            case"ymd":
                m = op.match(new RegExp("^((\\d{4})|(\\d{2}))([-./])(\\d{1,2})\\4(\\d{1,2})$"));
                if (m == null) return false;
                day = m[6];
                month = --m[5];
                year = (m[2].length == 4) ? m[2] : GetFullYear(parseInt(m[3], 10));
                break;
            case"dmy":
                m = op.match(new RegExp("^(\\d{1,2})([-./])(\\d{1,2})\\2((\\d{4})|(\\d{2}))$"));
                if (m == null)return false;
                day = m[1];
                month = --m[3];
                year = (m[5].length == 4) ? m[5] : GetFullYear(parseInt(m[6], 10));
                break;
            default:
                break;
        }
        if (isNaN(parseInt(month))) return false;
        month = month == 12 ? 0 : month;
        var date = new Date(year, month, day);
        return(typeof(date) == "object" && year == date.getFullYear() && month == date.getMonth() && day == date.getDate());
        function GetFullYear(y) {
            return((y < 30 ? "20" : "19") + y) | 0;
        }
   },
   ServerValidate:function(theform,methodName,validate){
	    var error={"retCode":"false","retMsg":""};
	    var theform = theform || event.srcElement;
		if (theform!=null){
             if (theform.tagName.toUpperCase()!="FORM"){
				 theform=theform.form;
             }
		}
		if (theform==null || theform.tagName.toUpperCase()!="FORM"){
			error["retMsg"]="没有定义form对象";
		    return error;
	    }
	   if (methodName==null){
		   methodName="formAction";
	   }
      if (validate==null){
         validate="Validate";
      }
	   var action=theform.action;
	   if (action==""){
		   error["retMsg"]="表单没有定义action属性！";
		   return error;
	   }
	   var hasMethod=false;
	   var fint=action.indexOf(methodName+"=");
	   if (fint>0){
		   hasMethod=true;
		   var lint=action.indexOf("&",fint+1)
		   if (lint==-1){
			   lint=action.length;
		   }
		   action=action.substring(0,lint)+validate+action.substring(lint);
	   }
	   var senddata="";
	   var objs=theform.elements;
	   var count=objs.length;
       for (var i = 0; i <count; i++) {
		   if (objs[i].name!=""){
			   var thevalue=objs[i].value;
               if ("checkbox"==objs[i].type){
                   if (!objs[i].checked){
                       thevalue="";
                   }
               }
			   if ("radio"==objs[i].type){
				   if (senddata.indexOf(""+objs[i].name+"=")>-1){
					   continue;
				   }else{
					   var radioobjs=document.getElementsByName(objs[i].name);
					   for (var r=0;r<radioobjs.length;r++){
						   if (radioobjs[r].checked){
							   thevalue=radioobjs[r].value;
                               r=radioobjs.length;
						   }
					   }
				   }
               }
               if (objs.name[i]==methodName){
				   if (hasMethod){
					   continue;
				   }else{
					   thevalue=objs[i].value+validate;
				   }
			   }
			   if (senddata!="") senddata+="&";
			   senddata+=objs[i].name+"="+encodeURIComponent(thevalue);
		   }
	   }
	   var retText=sendDataToServer(action,senddata,error);
	   if (retText!=null){
		   try{
		      return eval(retText+";");
		   }catch(e){
			  if (retText.indexOf("<TITLE>后台管理系统登陆</TITLE>")>-1 || retText.indexOf("<TITLE>宇通海外服务网</TITLE>">-1)){
                 error["retMsg"]="您登录的用户名已经在其它电脑上登录，请重新登录！"; 
			  }else if (retText.indexOf("<span style='color: #ff0000' id='errorContent'>")>-1){
				  var fint=retText.indexOf("<span style='color: #ff0000' id='errorContent'>");
				  if (fint!=-1){
					  var first=fint+"<span style='color: #ff0000' id='errorContent'>".length;
					  var lint=retText.indexOf("</span>",first);
					  var errorInfo="";
					  if (lint!=-1){
						  errorInfo=retText.substring(first,lint);
					  }else{
						  errorInfo=retText;
					  }
					  error["retMsg"]=errorInfo;
				  }
			  }else{
				 error["retMsg"]=retText;
			  }
		      return error; 
		   }
	   }else{
		   return error;
	   }
   }
}

function parseForm(formObj){
	var count = formObj.elements.length;
	for (var i = 0; i < count; i++) {
	   var obj=formObj.elements[i];
	   var _dataType=obj.getAttribute("dataType");
	   if (typeof(_dataType) != "object"){
		  if (_dataType.indexOf("UF_")!=-1){
			  //添加用户自定义验证
			  if (typeof(Validator[_dataType]) == "undefined"){
				 var ufFun=null;
				 try{
					 ufFun=eval(_dataType+"_Validate");
				 }catch(e){}
				 if (ufFun!=null && typeof(ufFun) == "function"){
					Validator[_dataType]=ufFun;
				 }
			  }
			  //添加onclick事件
			  if(typeof(obj.onclick) != "function"){
				 var ufFun=null;
				 try{
					 ufFun=eval(_dataType+"_OnClick");
				 }catch(e){}
				 if (ufFun!=null && typeof(ufFun) == "function"){
					obj.onclick=ufFun;//new Function(_dataType+"_OnClick(event)");
				 }
			  }
			  //添加onchange事件
			  if(typeof(obj.onchange) != "function"){
				 var ufFun=null;
				 try{
					 ufFun=eval(_dataType+"_OnChange");
				 }catch(e){}
				 if (ufFun!=null && typeof(ufFun) == "function"){
					obj.onchange=ufFun;
				 }
			  }
			  //添加onKeyPress事件
			  if(typeof(obj.onKeyPress) != "function"){
				 var ufFun=null;
				 try{
					 ufFun=eval(_dataType+"_OnKeyPress");
				 }catch(e){}
				 if (ufFun!=null && typeof(ufFun) == "function"){
					obj.onkeypress=ufFun;
				 }
			  }
			  //添加onblur事件
			  if(typeof(obj.onblur) != "function"){
				 var ufFun=null;
				 try{
					 ufFun=eval(_dataType+"_OnBlur");
				 }catch(e){}
				 if (ufFun!=null && typeof(ufFun) == "function"){
					obj.onblur=ufFun;
				 }
			  }
			  //添加onfocus事件
			  if(typeof(obj.onfocus) != "function"){
				 var ufFun=null;
				 try{
					 ufFun=eval(_dataType+"_OnFocus");
				 }catch(e){}
				 if (ufFun!=null && typeof(ufFun) == "function"){
					obj.onfocus=ufFun;
				 }
			  }
			  //添加查询按钮
			  var ufFun=null;
			  try{
				 ufFun=eval(_dataType+"_AddSearch");
			  }catch(e){}
			  if (ufFun!=null && typeof(ufFun) == "function"){
				 try{
				   ufFun(obj);
				 }catch(e){}
			  }
		  }   
	   }
	}
}

 //
function getEvent(evt){
  return evt ? evt : (window.event ? window.event : null);
}
function getEventObject(evt){
  evt =getEvent(evt); 
  return evt.srcElement?evt.srcElement:evt.target;
}

//<body onload="documentOnload()">
function documentOnload(){
	var fromLen=document.forms.length;
	for (var f=0;f<fromLen;f++){
		parseForm(document.forms[f]);
	}
}

function buttonInit(){
	var objs=document.getElementsByTagName("BUTTON")
	for (var i=0;i<objs.length;i++){
	   var fint=objs[i].innerHTML.indexOf("SPAN")
	   if (fint==-1){
		  objs[i].innerHTML="<span>"+objs[i].innerHTML+"</span>";
	   }
	}
}

//将form设为只读
function disableForm(formObj){
	var oEles = formObj.elements;
	for(var i=0; i<oEles.length; i++){
		if(oEles[i].type=="text" || oEles[i].type=="textarea" || oEles[i].type=="button" || oEles[i].type=="checkbox" || oEles[i].type=="file" || oEles[i].type=="radio" || oEles[i].type=="reset" || oEles[i].type=="select-one" || oEles[i].type=="select-multiple" || oEles[i].type=="submit"){
			oEles[i].disabled = true; //表单无效
		}
	}
	if(document.getElementById('btnTableId')!=null){
		document.getElementById('btnTableId').style.display="none";
	}
}

//form提交
var isGlobeSubmit=false;
function formSubmit(theform,checkFlag){
	if(isGlobeSubmit){
		alert("不能重复提交!");
		return;
	}
	if(checkFlag && !Validator.Validate(theform,1)){
		isGlobeSubmit=false;
		return;
	}
	try{showWait("数据处理中,请稍后......");}catch(e){}
	theform.submit();
	isGlobeSubmit=true;
 }


